var validator;
var $meetingAddForm = $("#meeting-add-form");

$(function () {
     $('#meeting-add-users').jstree({
        "core": {
            'multiple': true
        },
        "state": {
            "disabled": true
        },
        "checkbox": {
            "three_state": false
        },
        "plugins": ["wholerow", "checkbox"]
    });

    $("input[type=radio][name=meeting-repeat]").on('ifChecked change', function(event){ //modify by aaron.wei 2018.12.29
        var repeat = $(this).val();

        if (repeat == '3') {//fix meeting
        	$("#meeting-add .meeting-date").css({ display: "block" });
        	$("#meeting-add #meeting-duration").css({ display: "none" });
        	$("#meeting-add #meeting-repeat-day").css({ display: "none" });
            $("#meeting-add #meeting-repeat-end").css({ display: "block" });                                    
        }else if(repeat == '2'){//repeat meeting
        	$("#meeting-add .meeting-date").css({ display: "block" });
        	$("#meeting-add #meeting-duration").css({ display: "block" });
        	$("#meeting-add #meeting-repeat-day").css({ display: "block" });
            $("#meeting-add #meeting-repeat-end").css({ display: "block" });                        
        }else if(repeat == '1'){//once meeting
        	$("#meeting-add .meeting-date").css({ display: "block" });
        	$("#meeting-add #meeting-duration").css({ display: "block" });
        	$("#meeting-add #meeting-repeat-day").css({ display: "none" });
            $("#meeting-add #meeting-repeat-end").css({ display: "none" });
        }else{
            $("#meeting-add .meeting-date").css({ display: "none" });
            $("#meeting-add #meeting-duration").css({ display: "block" });
            $("#meeting-add #meeting-repeat-day").css({ display: "none" });
            $("#meeting-add #meeting-repeat-end").css({ display: "none" });
        }
    });

    $("#meeting-add .btn-save").click(function () {
        var repeat = $("input[type=radio][name=meeting-repeat]:checked").val();
        var repeatDay = new Array();
        var repeatEnd;

        var action = $("#meeting-add-form").attr("action");

        var meetingDate = $("input[name='meeting-date-link']").val();
        var meetingTime = $("input[name='meeting-time-link']").val();
        var durationId = $("select[name='duration']").val();

        if(repeat != '0' && (meetingDate == '' || meetingTime == '')) {
            $MB.n_warning($MB.i18n('meeting.tips.time.empty'));
            return;
        }

        if(durationId == -1 && repeat !== '3') {        	
        	$MB.n_warning($MB.i18n('meeting.select.hint.duration'));
        	return;        	
        }
        
        // chaohung , 20181228 , add fix meeting (start)
        if(repeat === '3') {
        	durationId=1;
        	repeatEnd = $("input[name='repeat-end-link']").val();
        	        	
            if(repeatEnd == '') {
                $MB.n_warning($MB.i18n('meeting.tips.end.empty'));
                return;
            }
        }
        // chaohung , 20181228 , add fix meeting (end)
        
        if(repeat === '2') {
            $("input[type=checkbox][name=repeat-day]:checked").each(function() {
                repeatDay.push($(this).attr('value'));
            });

            repeatEnd = $("input[name='repeat-end-link']").val();

            if(repeatDay.length == 0) {
                $MB.n_warning($MB.i18n('meeting.tips.repeat.empty'));
                return;
            }
            if(repeatEnd == '') {
                $MB.n_warning($MB.i18n('meeting.tips.end.empty'));
                return;
            }
        }

        var meetingPassword = $("input[name='meeting-password']").val();
        var moderatorPassword = $("input[name='moderator-password']").val();

        if(meetingPassword.length >0 && meetingPassword.length < 6) {
            $MB.n_warning($MB.i18n('meeting.tips.password.empty'));
            return;
        }

        if(moderatorPassword.length < 6) {
            $MB.n_warning($MB.i18n('meeting.tips.moderator.password.empty'));
            return;
        }

        var topic = $("input[name='topic']").val();
        var content = $("textarea[name='content']").val();

        if(topic.trim().length <= 0) {
            $MB.n_warning($MB.i18n('meeting.tips.topic.empty'));
            return;
        }

        if(content.trim().length <= 0) {
            $MB.n_warning($MB.i18n('meeting.tips.content.empty'));
            return;
        }


        var meetingRoomId=$("input[name='meetingroomId']").val();
        if(meetingRoomId.length==0){
           meetingRoomId=$("select[name='meeting-room']").val();
        }

        var users = $("#meeting-add-users").jstree(true).get_checked();
//        if(users.length == 0) {
//            $MB.n_warning($MB.i18n('meeting.tips.member.empty'));
//            return;
//        }
        
        // chaohung , 20181228 modify data 
        //var startTime;
        if (repeat != 3){
        	var duration = $("select[name='duration'] option:selected").attr("duration");
        }    	
        else{
        	var duration = -1;
        }

        // chaohung , 20181227 , meeting setting (start)
//        var meetingsettingmute =document.getElementById("meeting-list-setting-mute");
        var meetingsettingnoname =document.getElementById("meeting-list-setting-noname");
        var meetingsettingsayhi =document.getElementById("meeting-list-setting-sayhi");
        var meetingsettingshow =document.getElementById("meeting-list-setting-show");
        var meetingsettingtextsayhi =document.getElementById("meeting-list-setting-textsayhi");
        var meetingsettingrecorder =document.getElementById("meeting-list-setting-recorder");
        var meetingsettingdownloadshow =document.getElementById("meeting-list-setting-downloadshow");
//        var meetingsettingwbnote =document.getElementById("meeting-list-setting-wbnote");
        var meetingsettingsavewb =document.getElementById("meeting-list-setting-savewb");
        var meetingsettingautorecorder =document.getElementById("meeting-setting-autorecorder-auto");

        var setting = 0;
//        if(meetingsettingmute.checked){
//            setting |= (1 << 0);
//        }
        if(meetingsettingnoname.checked){
            setting |= (1 << 1);
        }
        if(meetingsettingsayhi.checked){
            setting |= (1 << 2);
        }
        if(meetingsettingshow.checked){
            setting |= (1 << 3);
        }
        if(meetingsettingtextsayhi.checked){
            setting |= (1 << 4);
        }
        if(meetingsettingrecorder.checked){
            setting |= (1 << 5);
        }
        if(meetingsettingdownloadshow.checked){
            setting |= (1 << 6);
        }
//        if(meetingsettingwbnote.checked){
//            setting |= (1 << 7);
//        }
        if(meetingsettingsavewb.checked){
            setting |= (1 << 8);
        }
        if(meetingsettingautorecorder.checked){
            setting |= (1 << 9);
        }
        // chaohung , 20181227 , meeting setting (end)
                
        //var repeatEnd;

        $(this).attr("disabled",true);

        var data = {
            "meetingRoomId": meetingRoomId,
            "meetingId": $("input[name='meeting-id']").val(),
            "topic": topic,
            "content": content,
            "startTime": repeat != '0' ? new Date(meetingDate + " " + meetingTime) : undefined,
            "duration": duration,
            "durationId": durationId,
            "repeatDay": repeatDay.join(),
            "repeatEnd": (repeat === '2' || repeat === '3') ? new Date(repeatEnd + " 23:59") : undefined,
            "users": users.join(),         
            "meetingPassword": meetingPassword,
            "moderatorPassword": moderatorPassword,
         // chaohung , 20181227 , meeting setting
            "setting": setting,
         // chaohung , 20181228 , fix meeting
            "type": repeat
        };

        if(action == "add") {
            $.post(ctx + "meeting/add", data, function (r) {
                if (r.code === 0) {
                    closeModal();
                    $MB.n_success(r.msg);
                    $MB.refreshTable("meetingTable");

                    // Add by Ken.he on 20190124 to add email ---Start---
                    sendAlertEmail(r.meetingId, 0);
                    // ---End---
                    if(calendar != null) {
                        calendar.view();
                    }
                } else {
                    $MB.n_danger(r.msg);
                }

                $("#meeting-add .btn-save").removeAttr("disabled");
            });
        } else {//edit
            var meetingId = $("#meeting-add-form").attr("meeting-id");

            $.post(ctx + "meeting/edit/" + meetingId, data, function (r) {
                if (r.code === 0) {
                    closeModal();
                    $MB.n_success(r.msg);
                    $MB.refreshTable("meetingTable");
                    // Add by Ken.he on 20190124 to add email ---Start---
                    sendAlertEmail(r.meetingId, 1);
                    // ---End---
                } else {
                    $MB.n_danger(r.msg);
                }

                $("#meeting-add .btn-save").removeAttr("disabled");
            });

        }
    });

    $("#meeting-add .btn-close").click(function () {
        closeModal();
    });
    
    // chaohung , 20190102        
    $("#meeting-list-setting-recorder").on('ifChecked change', function(event){ 
    	$("#meeting-recorder-setting").css({ display: "block" });
    	
    }); 
    $("#meeting-list-setting-recorder").on('ifUnchecked change', function(event){ 
    	$("#meeting-recorder-setting").css({ display: "none" });
    	
    });

    resetSetting();

    $('#repeat-now').iCheck('check');// modify by aaron.wei 2018.12.29
});

function doEditMeeting(meetingId) {
    $('#meeting-add-modal-title').text($MB.i18n('meeting.option.edit'));
    $.get(ctx + "meeting/edit/" + meetingId, function(r) {
        if(r.code == 0) {
            var meeting = r.msg;

            $meetingEditForm = $("#meeting-add-form")
            $meetingEditForm.attr("action", "edit");
            $meetingEditForm.attr("meeting-id", meeting.id);

            $meetingEditForm.find("#meeting-room-" + meeting.meetingRoomId).attr('selected','selected');
            $meetingEditForm.find("input[name='topic']").val(meeting.topic);
            $meetingEditForm.find("textarea[name='content']").val(meeting.content);

            var startTime = new Date(meeting.startTime);
            $("#meeting-date").val(startTime.format("yyyy-mm-dd"));
            $("#meeting-date-link").val(startTime.format("yyyy-mm-dd"));
            $("#meeting-time").val(startTime.format("hh:ii"));
            $("#meeting-time-link").val(startTime.format("hh:ii"));

//            $meetingEditForm.find("#duration-" + meeting.durationId).attr('selected','selected');
            document.getElementById("duration-" + meeting.durationId).selected = true;

            $("input[name='meeting-password']").val(meeting.meetingPassword);
            $("input[name='moderator-password']").val(meeting.moderatorPassword);

            $("#meeting-repeat").css("display", "none");

            updateSettings(meeting.setting);

            //即时会议不允许编辑
            if(meeting.type == '1') {
                $('#repeat-off').iCheck('check');
            } else if(meeting.type == '2') {//repeat meeting
                if(meeting.repeatParentId > 0) {//repeat child meeting
                    $('#repeat-off').iCheck('check');
                } else {//repeat parent meeting
                    $('#repeat-on').iCheck('check');
                    var repeatEnd = new Date(meeting.repeatEnd);
                    $("#repeat-end").val(repeatEnd.format("yyyy-mm-dd"));
                    $("#repeat-end-link").val(repeatEnd.format("yyyy-mm-dd"));

                    var days = meeting.repeatDay.split(",");

                    for(var i=0; i<days.length; i++) {
                        $("#repeat-day-" + days[i]).iCheck("check");
                    }
                }


            } else {//fixed meeting
                $('#repeat-fix').iCheck('check');

                var endTime = new Date(meeting.endTime);
                $("#repeat-end").val(endTime.format("yyyy-mm-dd"));
                $("#repeat-end-link").val(endTime.format("yyyy-mm-dd"));
            }

            var members = meeting.members;
            var jstree = $("#meeting-add-users").jstree(true);
            for(var i=0; i<members.length; i++) {
                jstree.check_node(members[i].user_id);
            }

            $('#meeting-add').modal();
        } else {
            $MB.n_danger(r.msg);
        }
    });
}

function closeModal() {
    $MB.closeAndRestModal("meeting-add");

    resetSetting();

    $('#repeat-now').iCheck('check');// modify by aaron.wei 2018.12.29
    $("#meeting-add .btn-save").removeAttr("disabled");

    $('#meeting-add-users').jstree(true).deselect_all();
    $("#meeting-add").find("#meeting-repeat").css({ display: "flex" });

    $('#meeting-duration').find('option').attr('selected', false); // add by aaron.wei 2018.12.29
    $('#meeting-duration').val('-1'); // add by aaron.wei 2018.12.29
    $('#meeting-add-modal-title').text($MB.i18n('meeting.option.add')); // add by aaron.wei 2018.12.29

    $("input[name='meeting-id']").val("");
}

function resetSetting() {
    $("#meeting-add").find(".icheckbox_minimal-tpv").each(function () {
        $(this).removeClass("checked");
    })

    $('#meeting-list-setting-noname').iCheck('check');
    $('#meeting-list-setting-show').iCheck('check');
    $('#meeting-list-setting-textsayhi').iCheck('check');
    $('#meeting-list-setting-recorder').iCheck('check');
    $('#meeting-list-setting-downloadshow').iCheck('check');

    $('#meeting-setting-autorecorder-manu').iCheck('check');
}

function updateSettings(setting) {
    var settingValue = parseInt(setting);

    if((settingValue & (1 << 1)) > 0){
        $("#meeting-list-setting-noname").iCheck('check');
    } else {
        $("#meeting-list-setting-noname").iCheck('uncheck');
    }

    if((settingValue & (1 << 2)) > 0){
        $("#meeting-list-setting-sayhi").iCheck('check');
    } else {
        $("#meeting-list-setting-sayhi").iCheck('uncheck');
    }

    if((settingValue & (1 << 3)) > 0){
        $("#meeting-list-setting-show").iCheck('check');
    } else {
        $("#meeting-list-setting-show").iCheck('uncheck');
    }

    if((settingValue & (1 << 4)) > 0){
        $("#meeting-list-setting-textsayhi").iCheck('check');
    } else {
        $("#meeting-list-setting-textsayhi").iCheck('uncheck');
    }

    if((settingValue & (1 << 5)) > 0){
        $("#meeting-list-setting-recorder").iCheck('check');
    } else {
        $("#meeting-list-setting-recorder").iCheck('uncheck');
    }
    if((settingValue & (1 << 6)) > 0){
        $("#meeting-list-setting-downloadshow").iCheck('check');
    } else {
        $("#meeting-list-setting-downloadshow").iCheck('uncheck');
    }

    if((settingValue & (1 << 8)) > 0){
        $("#meeting-list-setting-savewb").iCheck('check');
    } else {
        $("#meeting-list-setting-savewb").iCheck('uncheck');
    }

    if((settingValue & (1 << 9)) > 0){
        $("#meeting-setting-autorecorder-auto").iCheck('check');
    } else {
        $("#meeting-setting-autorecorder-manu").iCheck('check');
    }
}

function sendAlertEmail(meetingId, type) {
	console.log("sendAlertEmail---meetingId="+meetingId);
	$.post(ctx + "smtp/sendmail", {"meetingId": meetingId, "type":type}, function(r){
		console.log(r);
		if (r.code === 0) {
//            $MB.n_success($MB.i18n('email.send.success'));
        } else if(r.code === 1){
        	$MB.n_danger($MB.i18n('email.failtxt.configs.error'));
        } else if(r.code === 2){
        	$MB.n_danger($MB.i18n('email.failtxt.address.error'));
        } else if(r.code === -1){
        	$MB.n_danger($MB.i18n('email.failtxt.configs.off'));
        } else if(r.code === -2){
        	$MB.n_danger(r.msg);
        }else {
            $MB.n_danger(r.msg);
        }
	});
}